package com.zgc.util;

import com.jfoenix.controls.JFXDialog;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

public class JFXDialogUtil {

    private static final Logger logger = LoggerFactory.getLogger(JFXDialogUtil.class);

    /**
     * 移除 点击其他空白区域关闭窗口监听 （因无法直接获取所以使用反射获取）
     *
     * @param jfxDialog com.jfoenix.controls.JFXDialog
     */
    public static void removeEventHandler(JFXDialog jfxDialog) {
        try {
            jfxDialog.removeEventHandler(MouseEvent.MOUSE_PRESSED, getCloseHandler(jfxDialog));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            logger.error("弹窗[{}]，移除监听失败", jfxDialog.getClass(), e);
        }
    }

    /**
     * 添加 点击其他空白区域关闭窗口监听 （因无法直接获取所以使用反射获取）
     *
     * @param jfxDialog com.jfoenix.controls.JFXDialog
     */
    public static void addEventHandler(JFXDialog jfxDialog) {
        try {
            jfxDialog.addEventHandler(MouseEvent.MOUSE_PRESSED, getCloseHandler(jfxDialog));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            logger.error("弹窗[{}]，添加监听失败", jfxDialog.getClass(), e);
        }
    }

    @SuppressWarnings("unchecked")
    private static EventHandler<MouseEvent> getCloseHandler(JFXDialog jfxDialog) throws NoSuchFieldException, IllegalAccessException {
        Field field = jfxDialog.getClass().getDeclaredField("closeHandler");
        field.setAccessible(true);
        Object closeHandlerObject = field.get(jfxDialog);
        field.setAccessible(false);
        return (EventHandler<MouseEvent>) closeHandlerObject;
    }
}
